#!/usr/bin/python
#coding=utf-8

from StringIO import StringIO
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import requests

class SchoolNet(object):
	'''
		Login School Net
	'''
	__index_url = r'http://192.168.3.11:7001/QDHWSingle/login.jsp'
	__login_url = r'http://192.168.3.11:7001/QDHWSingle/login.do'
	__captcha_url = r'http://192.168.3.11:7001/QDHWSingle/ValidateCodeServlet?action=ShowValidateCode1'

	def __init__(self):
		self.__logName = None
		self.__logPW = None
		self.__validatecode = None
		self.__req_session = requests.Session()

	def get_captcha(self):
		'''
			Get captcha
		'''
		self.__req_session.get(SchoolNet.__index_url)
		__captcha_img = self.__req_session.get(SchoolNet.__captcha_url)
		
		img_file = open("image.jpg", "wb")
		img_file.write(__captcha_img.content)
		img_file.close()

		return StringIO(__captcha_img.content)

	def convertImgToString(self):
		import os
		cmd = "tesseract image.jpg outputdatabase digits"
		os.system(cmd)
		__validatecode = open("outputdatabase.txt").readline()[:4]
		os.system("rm -rf outputdatabase.txt image.jpg")

		return __validatecode

	def login(self, u, p, c):
		'''
			Login 
		'''
		self.__logName = u
		self.__logPW = p
		self.__validatecode = c
		payload = {
			'logName': self.__logName,
			'logPW': self.__logPW,
			'validatecode': self.__validatecode
		}

		result = self.__req_session.post(SchoolNet.__login_url, params=payload)

		return result

	def get_success_html(self):
		__success_url = r'http://192.168.3.11:7001/QDHWSingle/successqd.jsp'

		__html = self.__req_session.get(__success_url)

		return __html

if __name__ == '__main__':
	
	import sys
        import time

	data = SchoolNet()
	data.get_captcha()
	# cap = input('Validatecode: ')
	if sys.platform != 'linux2':
		cap = raw_input("Not Linux, try to open image file, and input validatecode: ")
	else:
		cap = data.convertImgToString()
	e = data.login('18765203305@qddx', '231503', cap)
	
        print "正在登录，请稍后..."
        time.sleep(10)
        #with open("success.html", "w") as success:
        info = requests.get(r'http://192.168.3.11:7001/QDHWSingle/successqd.jsp')
        success = 'logoff.do' # .decode('gbk')
        gbkinfo = info.text
        if success in gbkinfo:
            print "Congratulations. 登陆成功"
        else:
            print "Sorry, 请重新登录"
	#    success.write(info.content)

